/*
 * $RCSfile: RoomService.java,v $
 * $Revision: 1.1  $
 * $Date: 2012-8-15  $
 *
 * Copyright (C) 2005 Bettem, Inc. All rights reserved.
 *
 * This software is the proprietary information of Bettem, Inc.
 * Use is subject to license terms.
 */
package com.dzpk.gameserver.module.main.room;

import java.lang.reflect.Array;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import com.dzpk.gameserver.action.CommandEnum;
import com.dzpk.gameserver.module.main.*;
import com.dzpk.gameserver.module.main.cards.Card;
import com.dzpk.gameserver.module.main.pocer.Pocer;
import com.dzpk.gameserver.module.player.Player;
import com.dzpk.gameserver.protocol.MessageStruct;
import org.apache.log4j.Logger;


/**
 * 房间操作service
 * <p>Title: RoomService</p> 
 * <p>Description: </p> 
 * <p>Copyright: Copyright (c) 2006</p> 
 * @author shenxing.ruan
 * @version 1.0
 */
public class RoomService {
	private static Logger logger = Logger.getLogger(RoomService.class);
	public static final String sp = "@%";
	Room room;
	private RoomService (Room room) {
		this.room = room;
	}

	public static synchronized RoomService initRoomService(Room room) {
		return new RoomService(room);
	}
	private RoomService () {

	}

	/**
	 * 玩家站起
	 * @param rp
	 */
	public void zhangqi2(RoomPersion rp) {
		if (rp.getAddUpTime() > 1) {
			rp.setAddUpTimeLeiji(rp.getAddUpTimeLeiji() + (System.currentTimeMillis() - rp.getAddUpTime()));
			rp.setAddUpTime(0);
		}

		rp.setType(1);
		rp.setStatus(0);
		if (room.getRoomPersions()[rp.getSize()] != null && room.getRoomPersions()[rp.getSize()].getOnlinerType() != -1) {
			room.getRoomPersions()[rp.getSize()] = null;
		}
		room.getDdRoomPersions()[rp.getSize()] = null;
		//更新用户筹码
		if (room.getRoomType() == 1) {
			rp.setChouma(rp.getChouma() + rp.getNowcounma());
			rp.setNowcounma(0);
		}else {
			if (rp.getNowcounma() >= Constant.BI_SHAI_CHOU_MA) {
				rp.setChouma(rp.getChouma() + room.getChouma());
			}
			rp.setNowcounma(0);
		}
		//将绑定筹码解绑
//		try {
//			PersionChipBindDaoImp pcb = new PersionChipBindDaoImp();
//			pcb.updateChip(rp.getUserId(), 0);
//		} catch (Exception e) {
//			logger.error("解绑筹码出差....", e);
//		}
		try {
			updateChip(rp);
		} catch (SQLException e1) {
			e1.printStackTrace();
			logger.debug("更新筹码出错！！", e1);
		}
		//----------
		//通知别的玩家有人起来了
		byte[] bytes = MessageStruct.LeaveRoomResp.newBuilder().setIndex(rp.getSize()).setUserId(rp.getUserId()).build().toByteArray();
		this.broadcast(CommandEnum.S2C_LEAVE_ROOM_RESP, bytes);
		//通知本人站起成功

		bytes = MessageStruct.SeatActionResp.newBuilder().setState(2).setNowChouma(rp.getNowcounma()).setChoumaEnter(rp.getChouma()).build().toByteArray();
//		sendByUserId(bytes, rp.getUserId());
		rp.getUserInfo().getPlayer().sendMessage(CommandEnum.S2C_SEAT_OPT_RESP, bytes);
	}

	/**
	 * 玩家站起
	 *
	 * @param rp
	 */
	public synchronized void zhanqi(RoomPersion rp) {
		zhangqi2(rp);
	}


	/**
	 * 进入房间以游客的身份
	 * @param
	 * @return
	 */
	public synchronized void accessRoom(UserInfo userInfo) {
		//1、在线列表中有改用户则 直接T掉、并且已经在玩的做弃牌处理
		//2、 往在线列表中添加该用户

		if (room.getStatus() != 2) {
			return;
		}
		if (room.getAudMap().get(userInfo.getUserId()) != null) {
			// 已经在房间中了
			return;
		}
		accessRoom2(userInfo);
		byte[] bytes = getRoomDate2(-1);
		userInfo.getPlayer().sendMessage(CommandEnum.S2C_ENTER_ROOM_RESP, bytes);
	}

	public void accessRoom2(UserInfo userInfo) {
		userInfo.setOnlinetTime(System.currentTimeMillis());
		RoomPersion roomPersion = new RoomPersion();
		roomPersion.setUserId(userInfo.getUserId());
		roomPersion.setChouma(userInfo.getChip());
		roomPersion.setUserInfo(userInfo);
		room.getAudMap().put(userInfo.getUserId(), roomPersion);
		if (userInfo.getJixiren() == 0) {
			Cache.getOnlineUserInfo().put(userInfo.getUserId(), userInfo);
//			PersionLog.addCount(room.getRoomPath());
		}
		logger.debug("...down user id is : " + userInfo.getUserId() + " time is :" + System.currentTimeMillis());
	}

	//通知开始倒计时
	public synchronized void beginCountdown() {
		//通知开始倒计时
		try {
			//停顿1秒
			Thread.sleep(1000 * 1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		for (RoomPersion rp : room.getRoomPersions()) {
			if (rp != null) {
				rp.setType(4);
			}
		}
		logger.debug("通知开始倒计时.....room id :" + room.getRoomId());
		int time = (new Long(Constant.STATUS_2_DC/1000)).intValue();
		byte[] bytes = MessageStruct.PBInt.newBuilder().setValue(time).build().toByteArray();
		logger.debug("========= room.getMadLang:" + room.getAudMap().size());
		broadcast(CommandEnum.S2C_BEGIN_COUNT_DOWN, bytes);
	}

	/**
	 * 跟注
	 *
	 * @param roomPersion
	 * @param anteNumber
	 */
	public synchronized void genzhu(RoomPersion roomPersion , int anteNumber) {
		room.addActionCount();
		roomPersion.setNowcounma(roomPersion.getNowcounma() - anteNumber);
		roomPersion.setBetChouma((roomPersion.getBetChouma() < 0 ? 0 : roomPersion.getBetChouma()) + anteNumber);
		roomPersion.setAnteNumber(anteNumber);
		roomPersion.setStatus(2);
		roomPersion.setClientStatus(2);
		roomPersion.setAnteCount(roomPersion.getAnteCount() + anteNumber);
		room.setMaxChouma(roomPersion.getBetChouma());
		roomPersion.setBetStatus(1);
	}

	/**
	 * 加注
	 *
	 * @param roomPersion
	 * @param anteNumber
	 */
	public synchronized void jiazhu(RoomPersion roomPersion , int anteNumber) {
		room.addJiazhuCount();
		room.addActionCount();
		roomPersion.setNowcounma(roomPersion.getNowcounma() - anteNumber);
		roomPersion.setBetChouma((roomPersion.getBetChouma() < 0 ? 0 : roomPersion.getBetChouma()) + anteNumber);
		roomPersion.setAnteNumber(anteNumber);
		roomPersion.setStatus(2);
		roomPersion.setClientStatus(3);
		roomPersion.setAnteCount(roomPersion.getAnteCount() + anteNumber);
		room.setMaxChouma(roomPersion.getBetChouma());
		roomPersion.setBetStatus(1);
	}

	/**
	 * 全下
	 *
	 * @param roomPersion
	 * @param anteNumber
	 */
	public synchronized void quanxia(RoomPersion roomPersion , int anteNumber) {
		room.addActionCount();
		roomPersion.setNowcounma(0);
		roomPersion.setBetChouma((roomPersion.getBetChouma() < 0 ? 0 : roomPersion.getBetChouma()) + anteNumber);
		roomPersion.setAnteNumber(anteNumber);
		roomPersion.setStatus(3);
		roomPersion.setClientStatus(4);
		roomPersion.setAnteCount(roomPersion.getAnteCount() + anteNumber);
		room.setMaxChouma(roomPersion.getBetChouma() > room.getMaxChouma() ? roomPersion.getBetChouma() : room.getMaxChouma());
		roomPersion.setBetStatus(1);
	}

	/**
	 * 让牌
	 *
	 * @param roomPersion
	 */
	public synchronized void rangpai(RoomPersion roomPersion) {
		room.addActionCount();
		roomPersion.setStatus(1);
		roomPersion.setAnteNumber(0);
		roomPersion.setClientStatus(5);
		roomPersion.setBetStatus(2);
	}

	/**
	 * 弃牌
	 *
	 * @param roomPersion
	 */
	public synchronized void qipai(RoomPersion roomPersion) {
		room.addActionCount();
		roomPersion.setStatus(-3);
		roomPersion.setAnteNumber(0);
		roomPersion.setClientStatus(6);
		roomPersion.setBetStatus(2);
	}

	/**
	 * 关闭房间对象
	 */
	public void closeRoom2() {
		//保存用户
		for (RoomPersion rp : room.getRoomPersions()) {
			if (rp != null) {
				try {
					updateUserInfo(rp);
				} catch (Exception e) {
					logger.error("close room in save roomPersion err", e);
				}
			}
		}
		room.getAudMap().clear();
		long id = room.getRoomId();
		room.setRoomStatus(-999);
		Room leveRoom = Cache.getRoom(room.getRoomId());
		room.getRoomThread().close(id);
		Cache.deleteRoom(room.getRoomId());
		logger.debug("close room :" + id);
	}

	/**
	 * 关闭房间对象
	 */
	public synchronized void closeRoom() {
		closeRoom2();
	}

	/**
	 * 根据用户离开的相关状态做处理
	 */
	public void trimUserInfo(RoomPersion roomPersion) {
		if (roomPersion == null || roomPersion.getUserInfo() == null) {
			return;
		}
		//修改 积分/筹码相关
		UserInfo userInfo = roomPersion.getUserInfo();
		if (room.getRoomType() == 1) {
			if (room.getRoomStatus() > 2 && room.getRoomStatus() < 7 && roomPersion.getType() == 3) {
				userInfo.setLose(userInfo.getLose() + 1);
				roomPersion.setAc(roomPersion.getAc() + 1);
			}
		}else {
			//游戏中离开
			if (room.getBisaiStatus() == 2 && roomPersion.getType() == 3) {
				userInfo.setJifen2(userInfo.getJifen2() - 1);
				userInfo.setLose(userInfo.getLose() + 1);
				roomPersion.setAc(roomPersion.getAc() + 1);
			}
		}
	}

	public void likai2(RoomPersion persion , int type2) {
		if (persion.getUserInfo().getJixiren() ==0) {
//			PersionLog.rmCount(room.getRoomPath());
		}
		//还需要关闭socket 
//		persion.getUserInfo().getCline().clear();
		room.getAudMap().remove(persion.getUserId());
		Cache.getOnlineUserInfo().remove(persion.getUserId());
		//游戏中
		//1 设为掉线状态 2通知有人站起空出位置 3不发送消息
		//if (type2 == -1 && persion.getType() == 3) {
		if (persion.getType() == 3) {
			persion.setOnlinerType(-1);
			persion.setZdlk(1);
			try {
				trimUserInfo(persion);
				updateUserInfo(persion);
			} catch (SQLException e) {
				logger.error("更新用户信息出错!",e);
			}

		}else {
			//保存用户信息
			try {
				trimUserInfo(persion);
				updateUserInfo(persion);
			} catch (SQLException e) {
				logger.error("更新用户信息出错!",e);
			}
			if (persion.getSize() > -1) {
				if (room.getRoomPersions()[persion.getSize()] != null && room.getRoomPersions()[persion.getSize()].getOnlinerType() != -1) {
					room.getRoomPersions()[persion.getSize()] = null;
				}
				room.getDdRoomPersions()[persion.getSize()] = null;
			}
		}

		//该玩家已经坐下则要通知别的玩家有人起来了
		if (persion.getType() > 1) {
			byte[] bytes2 = MessageStruct.LeaveRoomResp.newBuilder().setIndex(persion.getSize()).setUserId(persion.getUserId()).build().toByteArray();
			sendExcept(CommandEnum.S2C_LEAVE_ROOM_RESP, bytes2, persion.getUserId());
		}

		//当前桌面玩家如果==2人情况下 倒计时时间设为0.5S
		int count = 0;
		for (RoomPersion rp : room.getRoomPersions()) {
			if (rp != null && rp.getOnlinerType() == 1) {
				count ++;
			}
		}

		//桌面只有1个玩家
		if (room.getRoomStatus() == 1 || room.getRoomStatus() == 2) { //非游戏
		}else { //游戏中
			if (count == 1) {
				room.setT3(-989);
			}
		}
	}

	/**
	 * 玩家二次进入房间时
	 * 通知别的玩家有人退出房间
	 * -1 不做任何操作 1失败 2逻辑往下走
	 */
	public synchronized int ercijinru(int userID , Player player , int action ,int roomId ,int roomPath) {
		RoomPersion persion = room.getAudMap().get(userID);
		if (persion == null) {
			return 2;
		}

		userTimeOut2(persion.getUserInfo());
		return 2;
	}
	/**
	 * 玩家二次进入房间时
	 * 通知别的玩家有人退出房间
	 * -1 不做任何操作 1失败 2逻辑往下走
	 */
	public synchronized int reconnectRoom(UserInfo userInfo , Player player , int action ,int roomId ,int roomPath) {
		RoomPersion persion = room.getAudMap().get(userInfo.getUserId());
		if (persion == null) {
			Cache.getOnlineUserInfo().remove(userInfo.getUserId());
			return 2;
		}
		persion.getUserInfo().setPlayer(player);
		persion.getUserInfo().setOnlinetTime(System.currentTimeMillis());
		userInfo.setOnlinetTime(System.currentTimeMillis());
		byte[] bytes = getRoomDate2( persion.getSize());
		persion.getUserInfo().getPlayer().sendMessage(CommandEnum.S2C_ENTER_ROOM_RESP, bytes);
		return -1;
	}
	/**
	 * 离开房间
	 *
	 */
	public synchronized void likai(RoomPersion persion , int type2) {
		likai2(persion , type2);
		byte[] bytes = MessageStruct.SeatActionResp.newBuilder().setNowChouma(persion.getNowcounma()).setChoumaEnter(persion.getChouma()).setState(1).build().toByteArray();
		persion.getUserInfo().getPlayer().sendMessage(CommandEnum.S2C_SEAT_OPT_RESP,bytes);
	}

	public byte[] fastGame2(int userId ,UserInfo userInfo ) {
		//验证是否有空位子
		int size = -1;
		for (int i = 0 ; i < room.getRoomPersions().length ; i ++) {
			RoomPersion rp = room.getRoomPersions()[i];
			if (rp == null || rp.getOnlinerType() == -1) {
				if (room.getDdRoomPersions()[i] == null) {
					size = i;
					break;
				}
			}
		}
		if (size == -1) {
			Object[][] objs2 = {
					{60,1,I366ClientPickUtil.TYPE_INT_1}
			};
			byte[] bytes = I366PickUtil.packAll(objs2, Constant.REQ_GAME_ENTER_ROOM);
			PublisherUtil.publisher(userInfo,bytes);
			return null;
		}
		//进入房间完成
		accessRoom2(userInfo);
		//做玩家坐下操作
		boolean b = downRoom2(userId , size);
		if (! b ) {
			logger.debug("进入房间失败....相关逻辑出错");
			Object[][] objs2 = {
					{60,1,I366ClientPickUtil.TYPE_INT_1}
			};
			byte[] bytes = I366PickUtil.packAll(objs2, Constant.REQ_GAME_ENTER_ROOM);
			PublisherUtil.publisher(userInfo,bytes);
			return new byte[]{-1};
		}
		RoomPersion roomPersion = room.getRoomPersions()[size];
		if (roomPersion == null || roomPersion.getOnlinerType() == -1) {
			roomPersion = room.getDdRoomPersions()[size];
		}

		Object[][] objs = {
				{132,userId,I366ClientPickUtil.TYPE_INT_4},
				{61,size,I366ClientPickUtil.TYPE_INT_1},
				{133,roomPersion.getNowcounma(),I366ClientPickUtil.TYPE_INT_4},
				{130,userInfo.getHead(),I366ClientPickUtil.TYPE_STRING_UTF16},
				{131,userInfo.getNikeName(),I366ClientPickUtil.TYPE_STRING_UTF16}
		};
		byte[] bytes2 = I366PickUtil.packAll(objs, Constant.REQ_GAME_RECV_SEAT_DOWN);
		send(bytes2 , userId); //通知有人进入房间

		if (size < 0) {
			Object[][] objs2 = {
					{60,1,I366ClientPickUtil.TYPE_INT_1}
			};
			byte[] bytes = I366PickUtil.packAll(objs2, Constant.REQ_GAME_ENTER_ROOM);
			PublisherUtil.publisher(userInfo,bytes); //通知房间数据
			return null;
		}else {
			byte[] bytes = getRoomDate2(Constant.REQ_GAME_ENTER_ROOM , size);
			PublisherUtil.publisher(userInfo,bytes);
			int a = 0;
			for (int i = 0  ; i < room.getDdRoomPersions().length ; i ++) {
				if (room.getDdRoomPersions()[i] != null || (room.getRoomPersions()[i] != null && room.getRoomPersions()[i].getOnlinerType() != -1)) {
					a ++;
				}
			}
			if (a == 2) {
				try {
					logger.debug("快速开始 延迟时间.....");
					Thread.sleep(500 * 3);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			return null;
		}
	}


	/**
	 * 玩家快速开始游戏
	 *
	 * @param userId 用户ID
	 * @return -1 快速开始游戏失败 >-1 返回座位编号
	 */
	public synchronized byte[] fastGame(int userId ,UserInfo userInfo ) {
		return fastGame2(userId , userInfo);
	}

	/**
	 * 请求做下
	 * @param userId
	 * @param seatId 座位号
	 * @return
	 */
	public synchronized int downRoom(int userId , int seatId , UserInfo userInfo) {

		boolean b = downRoom2(userId, seatId);
		//坐下失败
		if (!b) {
			logger.debug( "坐下失败" + " Processor_45_Seta id " + userId);
			return 1;
			//通知别的玩家有人坐下了
		}else {
			RoomPersion p = room.getRoomPersions()[seatId];
			if (p == null || p.getOnlinerType() == -1) {
				p = room.getDdRoomPersions()[seatId];
			}

			byte[] bytes = MessageStruct.BrocastSeatDown.newBuilder().setUserId(userId).setSeatId(seatId)
					.setChouma(p.getNowcounma()).setHead(p.getUserInfo().getHead()).setName(p.getUserInfo().getNikeName()).build().toByteArray();
			sendExcept(CommandEnum.S2C_SEAT_DOWN_2_ALL_RESP, bytes, userId);

			bytes = MessageStruct.SeatActionResp.newBuilder().setNowChouma(p.getNowcounma()).setChoumaEnter(p.getChouma()).setState(1).build().toByteArray();
			userInfo.getPlayer().sendMessage(CommandEnum.S2C_SEAT_OPT_RESP,bytes);
			if (room.getRoomType() == 2) {
				int a = 0;
				for (RoomPersion rp : room.getRoomPersions()) {
					if (rp != null) {
						a ++;
					}
				}
				if (a == RoomCourse.size) {
					try {
						Thread.sleep(1500);
					} catch (InterruptedException e) {
						e.printStackTrace();
						logger.debug("游戏场地，玩家人数满足个数准备开始游戏出错" + room.getRoomId(), e);
					}
				}
			}
			return -1;
		}
	}

	/**
	 * 请求做下
	 * @param userId
	 * @param size 座位号
	 * @return
	 */
	public boolean downRoom2(int userId , int size) {
		RoomPersion rp = room.getRoomPersions()[size];
		RoomPersion rpd = room.getDdRoomPersions()[size];
		RoomPersion roomPersion = room.getAudMap().get(userId);
		if (rpd != null || (rp != null && rp.getOnlinerType() != -1)) {
			return false;
		}

		if (roomPersion == null) {
			return false;
		}
		//比赛场地游戏中不给予坐下
		if (room.getRoomType() == 2 && room.getBisaiStatus() == 2) {
			return false;
		}
		//对应筹码两少于 服务费+大盲注时坐下失败
		int nowCount = roomPersion.getChouma() + roomPersion.getNowcounma();
		if (nowCount < room.getFuwufei() + room.getDamanzhu()) {
			return false;
		}



//		if (rp == null || rp.getOnlinerType() < 0) {
		//TODO 计入绑定
//		PersionChipBindDao pcb = new PersionChipBindDaoImp();
//		if (room.getRoomType() == 1) {
//			//携带量重小计算到大
//			int a = room.getMaxgold() - roomPersion.getNowcounma();
//			if (a <= roomPersion.getChouma()) {
//				roomPersion.setChouma(roomPersion.getChouma() - a);
//				roomPersion.setNowcounma(room.getMaxgold());
//			}else {
//				roomPersion.setNowcounma(roomPersion.getNowcounma() + roomPersion.getChouma());
//				roomPersion.setChouma(0);
//			}
//			//对筹码进行绑定
//			try {
//				pcb.initBind(roomPersion.getUserId(), roomPersion.getNowcounma(), room.getRoomId());
//			} catch (SQLException e) {
//				logger.error("....initBind ERR", e);
//			}
//		}else {
//			//比赛场地
//			if (roomPersion.getChouma() < room.getChouma() && roomPersion.getNowcounma() == 0) {
//				return false;
//			}
//			if (roomPersion.getNowcounma() == 0) {
//				roomPersion.setChouma(roomPersion.getChouma() - room.getChouma());
//				roomPersion.setNowcounma(Constant.BI_SHAI_CHOU_MA);
//			}
//			//对筹码进行绑定
//			try {
//				pcb.initBind(roomPersion.getUserId(), room.getChouma(), room.getRoomId());
//			} catch (SQLException e) {
//				logger.error("....initBind ERR", e);
//			}
//		}
//		if (roomPersion.getNowcounma() == 0) {
//			logger.error("down err.../userId/roomId/chouma:" + roomPersion.getUserId() + "/" + room.getRoomId() + "/" + roomPersion.getChouma());
//			return false;
//		}

		//更新玩家筹码
		try {
			updateChip(roomPersion);
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("玩家坐下添加筹码出差！", e);
		}

		roomPersion.setBetChouma(0);
		roomPersion.setAnteCount(0);

		//对于坐下的玩家初始化这些信息
		roomPersion.setUserId(userId);
		roomPersion.setStatus(0);
		roomPersion.setClientStatus(1);
		roomPersion.setType(2);
		roomPersion.setSize(size);
		roomPersion.setBetStatus(0);
		roomPersion.setAnteNumber(0);
		if (room.getRoomStatus() == 1 || room.getRoomStatus() == 2) { //非游戏
			room.getRoomPersions()[size] = roomPersion;
			roomPersion.setType(4);
		}else { //游戏中
			//往坐下列表中添加
			room.getDdRoomPersions()[size] = roomPersion;
			roomPersion.setType(4);
		}
//		}
		return true;
	}
	/**
	 * 设置大小盲注 庄家编号..已经存在则往后推一位 //玩家如果筹码不够则全下
	 */
	public void nextmanzhu() {
		//设置用户相关状态
		for (int i = 0 ; i < room.getRoomPersions().length ; i ++) {
			if (room.getRoomPersions()[i] != null) {
				room.getRoomPersions()[i].setStatus(0);
				room.getRoomPersions()[i].setClientStatus(1);
				room.getRoomPersions()[i].setAnteCount(0);
				room.getRoomPersions()[i].setBetChouma(0);
			}
		}

		//
		if (room.getZhuangjiaNumber() < 0 || room.getRoomPersions()[room.getZhuangjiaNumber()] == null) {
			//随机指定个专家
			int a = Room.getR().nextInt(8);
			for (int i = 0 ; i < room.getRoomPersions().length ; i ++) {
				if (a > 7) {
					a = 0;
				}
				if (room.getRoomPersions()[a] != null) {
					room.setZhuangjiaNumber(a);
					break;
				}
				a ++;
			}
		}

		//推一位
		for (int i = 0 ; i < room.getRoomPersions().length ; i ++) {
			room.zhuangjiaNumber ++;
			if (room.zhuangjiaNumber > 7) {
				room.zhuangjiaNumber = 0;
			}
			if (room.getRoomPersions()[room.zhuangjiaNumber] != null) {
				int a = room.zhuangjiaNumber;
				for (int i2 = 0 ; i2 < room.getRoomPersions().length ; i2 ++) {
					a ++;
					if (a > 7) {
						a = 0;
					}
					if (room.getRoomPersions()[a] != null) {
						room.manzhuNumber = a;
						RoomPersion rp = room.getRoomPersions()[a];
						//全下了
						if (rp.getNowcounma() <= room.getManzhu()) {
							rp.setBetChouma(rp.getNowcounma());
							rp.setAnteCount(rp.getBetChouma());
							rp.setNowcounma(0);
							rp.setStatus(3);
							rp.setClientStatus(4);
							room.setMaxChouma(rp.getBetChouma());
						}else {
							rp.setBetChouma(room.getManzhu());
							rp.setAnteCount(rp.getBetChouma());
							rp.setNowcounma(rp.getNowcounma() - room.getManzhu());
							rp.setStatus(2);
							rp.setClientStatus(1);
							room.setMaxChouma(rp.getBetChouma());
						}
						for (int i3 = 0 ; i3 < room.getRoomPersions().length ; i3 ++) {
							a ++;
							if (a > 7) {
								a = 0;
							}
							if (room.getRoomPersions()[a] != null) {
								room.damanzhuNumber = a;
								room.setCurrentNumber(room.damanzhuNumber);
								rp = room.getRoomPersions()[a];
								//全下了
								if (rp.getNowcounma() <= room.getDamanzhu()) {
									rp.setBetChouma(rp.getNowcounma());
									rp.setAnteCount(rp.getBetChouma());
									rp.setNowcounma(0);
									rp.setStatus(3);
									rp.setClientStatus(4);
									room.setMaxChouma(rp.getBetChouma());
								}else {
									rp.setBetChouma(room.getDamanzhu());
									rp.setAnteCount(rp.getBetChouma());
									rp.setNowcounma(rp.getNowcounma() - room.getDamanzhu());
									rp.setStatus(2);
									rp.setClientStatus(1);
									room.setMaxChouma(rp.getBetChouma());
								}
								nextCurrentNumber2();
								break;
							}
						}
						break;
					}
				}
				break;
			}
		}
//		currentNumber = -1;
		if (room.getManzhuNumber() < 0 || room.getDamanzhuNumber() < 0 || room.getManzhuNumber() > 7 || room.getDamanzhuNumber() > 7 || room.getZhuangjiaNumber() < 0 || room.getZhuangjiaNumber() > 7 || room.getRoomPersions()[room.getZhuangjiaNumber()] == null || room.getRoomPersions()[room.getManzhuNumber()] == null || room.getRoomPersions()[room.getDamanzhuNumber()] == null) {
			logs();
		}
	}

	/**
	 * 往后推一位 下注 返回玩家ID
	 */
	public synchronized long nextCurrentNumber() {
		return nextCurrentNumber2();
	}


	/**
	 * 往后推一位 下注 返回玩家ID
	 */
	public long nextCurrentNumber2() {
		if (room.getCurrentNumber() < 0) {
			room.setCurrentNumber(room.damanzhuNumber);
		}
		int CurrentNumber = room.getCurrentNumber();
//		logger.debug("1------nextCurrentNumber2 currNumber/userId:" + CurrentNumber + "/" + room.getRoomPersions()[room.getCurrentNumber()].getUserId());
		RoomPersion roomPersion = null;
		for (int i3 = 0 ; i3 < room.getRoomPersions().length ; i3 ++) {
//			room.setCurrentNumber(room.getCurrentNumber() + 1);
			CurrentNumber ++;
			if (CurrentNumber > 7) {
				CurrentNumber = 0;
			}
			roomPersion = room.getRoomPersions()[CurrentNumber];
			if (roomPersion != null && roomPersion.getStatus() != 3
					&& roomPersion.getStatus() != -2
					&& roomPersion.getStatus() != -3
					&& roomPersion.getOnlinerType() ==1
					) {
				room.setCurrentNumber(CurrentNumber);
//				logger.debug("2------nextCurrentNumber2 currNumber/userId/roomSize:" + room.getCurrentNumber() + "/" + room.getRoomPersions()[room.getCurrentNumber()].getUserId());
				return roomPersion.getUserId();
			}else {
//				logger.debug("userId / status:" + (roomPersion == null ? "" : (roomPersion.getUserId() + "/"+ roomPersion.getStatus())));
			}
		}
		return -1;
	}

	/**
	 * 玩家添加筹码
	 *
	 * @param newUpChouma
	 * @param chips
	 * @return
	 */
	public synchronized int addChip(int userId , int newUpChouma , int chips ) {
		RoomPersion roomPersion = room.getAudMap().get(userId);
		if (room.getRoomStatus() > 2) {
			return 1;
		}
		roomPersion.setChouma(roomPersion.getChouma() + newUpChouma);
		if (roomPersion.getChouma() < chips) {
			return 1;
		}
		//
		int a_ = roomPersion.getNowcounma() + chips;
		if (a_ < (roomPersion.getChouchuStatus() * (-1))) {
			return 1;
		}
		if (room.getRoomType() == 1) {
			int a = roomPersion.getNowcounma() + chips;
//			if (a <= room.getChouma()) {
			roomPersion.setNowcounma(a + roomPersion.getChouchuStatus());
			roomPersion.setChouchuStatus(0);
			roomPersion.setChouma(roomPersion.getChouma() - chips);
//			}
		}else {
			if (chips < room.getChouma()) {
				return 1;
			}
			roomPersion.setNowcounma(Constant.BI_SHAI_CHOU_MA);
			roomPersion.setChouma(roomPersion.getChouma() - room.getChouma());
		}

		//更新玩家筹码
		try {
			updateChip(roomPersion);
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("玩家坐下添加筹码出差！", e);
		}
		//通知别的玩家有人带了筹码
		byte[] bytes = MessageStruct.FreshChips.newBuilder().setUserId(roomPersion.getUserId()).setNowChouma(roomPersion.getNowcounma())
				.setSeatId(roomPersion.getSize()).build().toByteArray();

		broadcast(CommandEnum.S2C_FRESH_CHIPS, bytes);
		return 0;
	}


	/**
	 * 更新筹码量
	 *
	 * @param roomPersion
	 * @throws SQLException
	 */
	public void updateChip(RoomPersion roomPersion)  throws SQLException{
//		UserInfoDao userInfoDao = new UserInfoDaoImp();
//		try {
//			userInfoDao.updateChip(roomPersion.getUserId(), roomPersion.getChouma() - roomPersion.getUserInfo().getChip());
//			roomPersion.getUserInfo().setChip(roomPersion.getChouma());
//		} catch (SQLException e) {
//			logger.error("更新用户筹码数量出错！", e);
//			e.printStackTrace();
//			throw e;
//		}


	}

	/**
	 * 赠送筹码相关
	 * @param chip
	 * @param roomPersion
	 * @return
	 */
//	public synchronized void liwu(int chip ,RoomPersion roomPersion , int fromSeat , int toSeat , int giftID , RoomPersion inRoomPersion , UserProductByList userProductByList) {
//		int status = 0;
//		if (userProductByList != null) {
//			userProductByList.setGifCount(userProductByList.getGifCount() - 1);
//			UserInfoDao userInfoDao = new UserInfoDaoImp();
//			userInfoDao.updateUserProductByList(userProductByList.getUserId());
//		}else {
//			roomPersion.setChouma(roomPersion.getChouma() - chip);
//			try {
//				updateChip(roomPersion);
//				if (giftID == 0) {
//					inRoomPersion.setChouma(inRoomPersion.getChouma() + chip);
//					updateChip(inRoomPersion);
//				}
//			} catch (SQLException e) {
//				status = -1;
//			}
//		}
//		if (userProductByList == null) {
//			userProductByList = Cache.getOnlineUserInfo().get(roomPersion.getUserId()).getUserProductByList();
//		}
//		Object[][] objs = {
//				{60,status,I366PickUtil.TYPE_INT_1},
//				{61,fromSeat,I366PickUtil.TYPE_INT_1},
//				{62,toSeat,I366PickUtil.TYPE_INT_1},
//				{63,giftID,I366PickUtil.TYPE_INT_1},
//				{64,giftID == 0 ? 0 : (userProductByList == null ? 1 : 2),I366PickUtil.TYPE_INT_1},
//				{130,chip,I366PickUtil.TYPE_INT_4},
//				{131,userProductByList == null ? 0 : userProductByList.getGifCount(),I366PickUtil.TYPE_INT_4}
//		};
//		byte[] bytes = I366PickUtil.packAll(objs, Constant.REQ_GAME_USE_GIFT);
//		if (status == 0) {
//			send(bytes);
//		}else {
//			sendByUserId(bytes, roomPersion.getUserId());
//		}
//
//	}

	/**
	 * 倒计时相关
	 * @param roomPersion
	 * @param chip
	 * @param huods
	 * @param times
	 * @param honus_next
	 */
//	public synchronized void daojishi(RoomPersion roomPersion , int chip , int[] huods , int times , int honus_next ) {
//		int status = 0;
//		if (huods != null) {
//			roomPersion.setChouma(roomPersion.getChouma() + chip);
//			try {
//				updateChip(roomPersion);
//			} catch (SQLException e) {
//				status = -1;
//			}
//		}
//		Object[][] objs = {
//				{60,status,I366PickUtil.TYPE_INT_1},
//				{130,chip,I366PickUtil.TYPE_INT_4},
//				{131,times,I366PickUtil.TYPE_INT_4},
//				{132,honus_next,I366PickUtil.TYPE_INT_4},
//		};
//		byte[] bytes = I366PickUtil.packAll(objs, Constant.REQ_GET_COUNTDOWN_HONUS);
//		sendByUserId(bytes, roomPersion.getUserId());
//	}


	/**
	 * 玩家没有坐下离开
	 * @param userId
	 * @return
	 */
	public synchronized RoomPersion noDownLikai(int userId) {
		RoomPersion persion = room.getAudMap().get(userId);
		if (persion != null) {
//			PersionLog.rmCount(room.getRoomPath());
			if (persion.getSize() > -1) {
				try {
					room.getRoomService().updateUserInfo(persion);
				} catch (SQLException e) {
					logger.error("li kai err", e);
				}
			}
			room.getAudMap().remove(userId);
			Cache.getOnlineUserInfo().remove(userId);
		}

		return persion;
	}

	/**
	 * 更新用户基本信息 (最大手牌 最大手牌类型 最高拥有筹码 剩余多少筹码 )
	 */
	public UserInfo updateUserInfo(RoomPersion roomPersion) throws SQLException{
		//将绑定筹码解绑
		try {
			PersionChipBindDaoImp pcb = new PersionChipBindDaoImp();
			pcb.updateChip(roomPersion.getUserId(), 0);
		} catch (Exception e) {
			logger.error("解绑筹码出差....", e);
		}
		//有玩过游戏
		if (roomPersion.getIsGame() > 0 || roomPersion.getSize() > -1) {
			UserInfoDao userInfoDao = new UserInfoDaoImp();
			String nut = "";
			UserInfo userInfo = roomPersion.getUserInfo();
			if (userInfo.getPocer()[0] != null) {
				nut = getNut(userInfo.getPocer()[0].getSize1()) + getNut(userInfo.getPocer()[1].getSize1()) + getNut(userInfo.getPocer()[2].getSize1()) + getNut(userInfo.getPocer()[3].getSize1())
						+ getNut(userInfo.getPocer()[4].getSize1());
				userInfo.setNutHand(nut);
			}
			userInfo.setNutHandType(userInfo.getPocerType());


			//修改 积分/筹码相关

			if (room.getRoomType() == 1) {
				roomPersion.setChouma(roomPersion.getNowcounma() + roomPersion.getChouma());
				roomPersion.setNowcounma(0);
				if (roomPersion.getChouma() > userInfo.getHighestHave()) {
					userInfo.setHighestHave(roomPersion.getChouma());
				}
				updateChip(roomPersion);
			}else {
//				roomPersion.setChouma(roomPersion.getNowcounma() + roomPersion.getChouma());
				//如果游戏还有没有开始 掉线/或者离开
				if (roomPersion.getNowcounma() >= Constant.BI_SHAI_CHOU_MA && roomPersion.getType() != 3) {
					roomPersion.setChouma(roomPersion.getChouma() + room.getChouma());
				}
				roomPersion.setNowcounma(0);
				//比赛产地
				if (roomPersion.getChouma() > userInfo.getHighestHave()) {
					userInfo.setHighestHave(roomPersion.getChouma());
				}
				updateChip(roomPersion);
			}
			// 活动逻辑处理
			try {
				huodong(roomPersion);
				userInfoDao.updateRow(userInfo);
			} catch (SQLException e) {
				logger.error("保存用户信息出错！！", e);
				e.printStackTrace();
				throw e;
			}
			//对于游戏中离开的玩家给用记录
			roomPersion.setLastChouma(roomPersion.getBetChouma());
			room.getDeletePersion().putPersion(roomPersion);

			return userInfo;
		}
		return roomPersion.getUserInfo();

	}

	private void huodong(RoomPersion roomPersion) {
//		Long l;
//		if ( roomPersion.getAddUpTime() < 100) {
//			l = new Long(roomPersion.getAddUpTimeLeiji()/1000/60);
//		}else {
//			l =	(System.currentTimeMillis() - roomPersion.getAddUpTime() + roomPersion.getAddUpTimeLeiji())/1000/60;
//		}
//		roomPersion.setAddUpTime(0);
//		roomPersion.setAt(l.intValue());
		//-----
		if (roomPersion.getUserInfo().getJixiren() == 0) {
//			UserInfoDao userInfoDao = new UserInfoDaoImp();
//			try {
//				userInfoDao.addHuoDong(new String[0], is);
//			} catch (Exception e) {
//				logger.debug("....update user info err", e);
//			}
		}
	}

	private String getNut(int i) {
		if (i < 10) {
			return "0" + i;
		}
		return String.valueOf(i);
	}



	/**
	 * 重新开始一局
	 */
	public synchronized void nextGame() {
		if (room.getRoomType() == 1) {
			//清理掉线玩家
			for (int i = 0 ; i < room.getRoomPersions().length ; i ++) {
				RoomPersion rp = room.getRoomPersions()[i];
				if (rp != null && rp.getOnlinerType() < 0 ) {
					room.getRoomPersions()[i] = null;
					try {
						if (rp.getZdlk() == -1) {
							updateUserInfo(rp);
						}
					} catch (SQLException e) {
						logger.error("更新用户信息",e);
					}
					rp = null;
				}
				if (rp != null && rp.getStatus() == -2 && rp.getZdlk() == -1) {
					zhangqi2(rp);
					//站起的是机器人 则把机器人返回
//					if (rp.getUserInfo().getJixiren() == 1) {
//						Robot[] robots = new Robot[1];
//						robots[0] = room.getRobotManage().getRobots().get(rp.getUserId());
//						room.getRobotManage().recoverRobot(robots);
//					}
				}

				rp = room.getDdRoomPersions()[i];
				if (rp != null && rp.getOnlinerType() < 0) {
					room.getRoomPersions()[i] = null;
					try {
						if (rp.getZdlk() == -1) {
							updateUserInfo(rp);
						}
					} catch (SQLException e) {
						logger.error("更新用户信息",e);
					}
					rp = null;
				}
			}

			//解除玩家游戏状态
			for (int i = 0 ; i < room.getRoomPersions().length ; i ++) {
				if (room.getRoomPersions()[i] != null) {
					if (room.getRoomType() == 1) {
						room.getRoomPersions()[i].setType(4);//坐下等待开始
					}
				}
			}
			//落实等待的人
			for (int i = 0 ; i < room.getDdRoomPersions().length ; i ++) {
				RoomPersion rp = room.getDdRoomPersions()[i];
				if (rp != null) {
					room.getRoomPersions()[rp.getSize()] = rp;
					room.getDdRoomPersions()[i] = null;
				}
			}
		}
		room.reset();
		room.nextGame();
	}

	/**
	 * 通知比牌结果
	 */
	private  int bipaijieguo(RoomPersion[][] rpss) {

		Integer[] iswin = new Integer[8];
		Integer[] seatIdArray = new Integer[8];
		Long[] playerIdArray = new Long[8];
		Integer[] chipsArray = new Integer[8];
		Integer[] cardsTypeArray = new Integer[8];
		Integer[] cardsSort = new Integer[8 * 7];
		Integer[] newChipsArray = new Integer[8];
		Long[] allIds = new Long[8];

		Integer[] firstCardArray = new Integer[8];
		Integer[] secondCardArray = new Integer[8];
		Integer[] ismaxcardArray = new Integer[8];
		int k1 = 0;
		int k2 = 0;
		int winCount = 0;
		for (int i1 = 0 ; i1 < rpss.length ; i1 ++) {
			RoomPersion[] rps = rpss[i1];
			//玩家要拿回去的筹码...不一定是赢的玩家
			if (rps != null && rps.length > 0 && rps[0] != null ) {//&& (rps[0].getLastChouma() + rps[0].getYq()) > 0) {
				for (int j1 = 0 ; j1 < rps.length ; j1 ++) {
					RoomPersion rp = rps[j1];
					if (rp != null && rp.getOnlinerType() == 1 && room.getAudMap().get(rp.getUserId()) != null) {
						if (rp.getLastChouma() + rp.getYq() > 0) {
							iswin[k1] = rp.getYq() > 0 ? 0 : 1;
							if (iswin[k1] == 0) {
								winCount ++;
							}
							seatIdArray[k1] = rp.getSize();
							playerIdArray[k1] = rp.getUserId();
							chipsArray[k1] = rp.getYq() + rp.getLastChouma();
							cardsTypeArray[k1] = rp.getPocerType();
							for (int n = 0 ; n < room.getPocer().length ; n ++) {
								Pocer pocer1 = room.getPocer()[n];
								for (int j = 0 ; j < rp.getZuidaPocers().length ; j ++) {
									Pocer pocer2 = rp.getZuidaPocers()[j];
									if (pocer1.getSize1() == pocer2.getSize1()) {
										cardsSort[k2] = n;
										k2 ++;
										break;
									}
								}
							}
							for (int n = 5 ; n < 7 ; n ++) {
								Pocer pocer1 = rp.getPocers()[n - 5];
								for (int j = 0 ; j < rp.getZuidaPocers().length ; j ++) {
									Pocer pocer2 = rp.getZuidaPocers()[j];
									if (pocer1.getSize1() == pocer2.getSize1()) {
										cardsSort[k2] = n;
										k2 ++;
										break;
									}
								}
							}
							k1 ++;
						}
					}else {
//						if (rp != null) {
//							logger.debug("玩家掉线了 不通知比赛结果了...." + rp.getUserId());
//						}
						break;
					}
				}
			}else {
				break;
			}
		}

		for (int i = 0 ; i < room.getRoomPersions().length ; i ++) {
			RoomPersion rp = room.getRoomPersions()[i];
			if (rp != null && rp.getOnlinerType() > 0) {
				newChipsArray[i] = rp.getNowcounma();
				allIds[i] = rp.getUserId();
				//玩家第一,2 张牌 是否取得最大赢取
				firstCardArray[i] = rp.getPocers()[0].getSize1();
				secondCardArray[i] = rp.getPocers()[1].getSize1();
				if (rp.getUserInfo().getIsBiggestwinRate() == 1) {
					ismaxcardArray[i] = 0;
				}else {
					ismaxcardArray[i] = 1;
				}
			}else {
				newChipsArray[i] = -1;
				allIds[i] = -1L;
				//玩家第一,2 张牌 是否取得最大赢取
				firstCardArray[i] = -1;
				secondCardArray[i] = -1;
				ismaxcardArray[i] = -1;
			}
		}
		if (k1 == 0) {
			logger.error("not final ..");
		}
		Integer[] seatIdArray_ = new Integer[k1];
		Long[] playerIdArray_ = new Long[k1];
		Integer[] chipsArray_ = new Integer[k1];
		Integer[] cardsTypeArray_ = new Integer[k1];
		Integer[] iswin_ = new Integer[k1];

		Integer[] cardsSort_ = new Integer[k2];
//		Integer[] firstCardArray_ = new Integer[k1];
//		Integer[] secondCardArray_ = new Integer[k1];
//		Integer[] ismaxcardArray_ = new Integer[k1];

		System.arraycopy(seatIdArray,0,seatIdArray_,0,k1);
		System.arraycopy(playerIdArray,0,playerIdArray_,0,k1);
		System.arraycopy(chipsArray,0,chipsArray_,0,k1);
		System.arraycopy(cardsTypeArray,0,cardsTypeArray_,0,k1);
		System.arraycopy(iswin,0,iswin_,0,k1);

		System.arraycopy(cardsSort,0,cardsSort_,0,k2);
//		System.arraycopy(firstCardArray,0,firstCardArray_,0,k1);
//		System.arraycopy(secondCardArray,0,secondCardArray_,0,k1);
//		System.arraycopy(ismaxcardArray,0,ismaxcardArray_,0,k1);



		MessageStruct.GameResult.Builder builder = MessageStruct.GameResult.newBuilder();
		builder.addAllSeatIds(Arrays.asList(seatIdArray_));
		builder.addAllUserList(Arrays.asList(playerIdArray_));
		builder.addAllChipsList(Arrays.asList(chipsArray_));
		builder.addAllCardTypeList(Arrays.asList(cardsTypeArray_));
		builder.addAllCardSortList(Arrays.asList(cardsSort_));
		builder.addAllNewChipList(Arrays.asList(newChipsArray));
		builder.addAllAllUserList(Arrays.asList(allIds));
		builder.addAllFirstCardList(Arrays.asList(firstCardArray));
		builder.addAllSecondCardList(Arrays.asList(secondCardArray));
		builder.addAllIsmaxcardList(Arrays.asList(ismaxcardArray));
		builder.addAllIsWinList(Arrays.asList(iswin_));
		byte[] bytes = builder.build().toByteArray();
		broadcast(CommandEnum.S2C_ROUND_RESULT, bytes);
		return winCount;
	}

	/**
	 * 比牌
	 */
	public synchronized Object[] bipai() {
		Object[] objs = new Object[10];
		try {
			//通知比赛结果之前停个1秒 用户翻牌操作
			Thread.sleep(1 * 1000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		logger.debug("bi pai ...");
		RoomPersion[] rps = room.getRoomPersions();
		//算牌
		int size = -1;
		for (int i = 0 ; i < rps.length ; i ++) {
			if (rps[i] != null) {
				Pocer[] pocer = new Pocer[7];
				pocer[0] = room.getPocer()[0];
				pocer[1] = room.getPocer()[1];
				pocer[2] = room.getPocer()[2];
				pocer[3] = room.getPocer()[3];
				pocer[4] = room.getPocer()[4];
				pocer[5] = rps[i].getPocers()[0];
				pocer[6] = rps[i].getPocers()[1];
				Object[] obj = zuidapai(pocer);

				pocer = (Pocer[])obj[0];
				rps[i].setZuidaPocers(pocer);
				rps[i].setPocerType((Integer)obj[1]);
//				rps[i].getUserInfo().setPocerType((Integer)obj[1]);
				rps[i].setLastChouma(rps[i].getBetChouma());
				rps[i].setYq(0);
				rps[i].setYs(-1);
				size ++;
			}
		}
		RoomPersion[] rps2 = new RoomPersion[size + 1];
		for (int i = 0 ; i < rps.length ; i ++) {
			if (rps[i] != null) {
				//更新最大手牌
				if (rps[i].getUserInfo().getPocer()[0] == null) {
					rps[i].getUserInfo().setPocer(rps[i].getZuidaPocers());
					rps[i].getUserInfo().setPocerType(rps[i].getPocerType());
				}else {
					RoomPersion r = new RoomPersion();
					r.setZuidaPocers(rps[i].getUserInfo().getPocer());
					r.setPocerType(rps[i].getUserInfo().getPocerType());
					if (bipai2(rps[i] , r) == 0) {
						rps[i].getUserInfo().setPocer(rps[i].getZuidaPocers());
						rps[i].getUserInfo().setPocerType(rps[i].getPocerType());
					}
				}
				rps2[size] = rps[i];
				size --;
			}
		}
		RoomPersion[][] rpss = new RoomPersion[8][8]; //分组集合
		int[] geshu = {-1,-1,-1,-1,-1,-1,-1,-1};
		//rps2冒泡排序
		//1 对牌大小进行排序 重小到大
		for (int i = 0; i < rps2.length; i++) {
			for (int j = 0; j < rps2.length - i - 1; j++) {
				if (bipai2(rps2[j],rps2[j+1]) == 1){// 小的往上冒,由大到小
					swap(rps2, j, j + 1);
				}
			}
		}
		//--------------------------打印牌重大到小-------------------------
		for (RoomPersion rp : rps2) {
			if (rp == null ) {
				continue;
			}
			for (Pocer p : rp.getZuidaPocers()) {
				logger.debug(p.getName());
			}
			int pocerType = rp.getPocerType();
			logger.debug("roomId/userId/status:" +room.getRoomId()+ " " +rp.getUserId()+ " " + rp.getStatus() + "  这是：" + (pocerType == 1 ? "皇家同花顺" : pocerType == 2 ? "同花顺" : pocerType == 3 ? "四条" : pocerType == 4 ? "葫芦" : pocerType == 5 ? "同花" : pocerType == 6 ? "顺子" : pocerType == 7 ? "三条" : pocerType == 8 ? "两对" : pocerType == 9 ? "一对" : "高牌"));
		}

		int g_ = 0;
		//将牌按照 排名组装成二维数组
		for (int i = 0; i < rps2.length - 1; i++) {
			int j = bipai2(rps2[i] , rps2[i + 1]);
			if (j == -1) {
				if (geshu[g_] == -1) {
					geshu[g_] = 0;
				}
				geshu[g_] = geshu[g_] + 1;
				rpss[g_][geshu[g_] - 1] = rps2[i];
				rpss[g_][geshu[g_]] = rps2[i + 1];
			}else {
				if (geshu[g_] == -1) {
					geshu[g_] = 0;
				}
				rpss[g_][geshu[g_]] = rps2[i];

				g_ ++;
				geshu[g_] = 0;
				rpss[g_][geshu[g_]] = rps2[i + 1];
			}
		}
		//离开的人设置输赢
//		for (int u = 0 ; u < room.getDeletePersion().getSize() ; u ++) {
//			RoomPersion ur = room.getDeletePersion().getRoomPrsions()[u];
//			ur.setYq(-ur.getBetChouma());
//		}

		//分配奖金 这里只修改
		for (int i = 0 ; i < rpss.length ; i ++) {
//			if (i == rpss.length - 1 || rpss[i + 1][0] == null) {
//				break;
//			}
			if (geshu[i] == -1) {
				break;
			}
			int count = 0;
			for (int j = 0 ; j < geshu[i] + 1 ; j ++) {
				if (rpss[i][j].getBetChouma() < 1) {
					continue;
				}
				count = count + rpss[i][j].getBetChouma();
				for (int e = 0; e < rps2.length ; e ++) {
					if (rps2[e] != null && rpss[i][j].getUserId() == rps2[e].getUserId()) {
						rps2[e] = null;
					}
				}
			}
			double yq = 0;
			for (int k = 0 ; k < rps2.length ; k ++) {
				if (rps2[k] == null) {
					continue;
				}
				int b = rps2[k].getBetChouma() - count;
				if (b == 0) {
					rps2[k].setYq(rps2[k].getYq() - count);
					rps2[k].setBetChouma(0);
					yq = yq + count;
					//不用比了
					rps2[k] = null;
				} else if (b > 0) {
					rps2[k].setYq(rps2[k].getYq() - count);
					rps2[k].setBetChouma(b);
					yq = yq + count;
				}else {
					yq = yq + rps2[k].getBetChouma();
					rps2[k].setYq(rps2[k].getYq()  -rps2[k].getBetChouma());
					rps2[k].setBetChouma(0);
					//不用比了
					rps2[k] = null;
				}
			}
			//添加赢取离开人的筹码
//			for (int u = 0 ; u < room.getDeletePersion().getSize() ; u ++) {
//				RoomPersion ur = room.getDeletePersion().getRoomPrsions()[u];
//				if (ur.getBetChouma() > 0) {
//					int b = ur.getBetChouma() - count;
//					if (b == 0) {
//						yq = yq + count;
//						ur.setBetChouma(0);
//					}else if (b > 0) { 
//						ur.setBetChouma(b);
//						yq = yq + count;
//					}else {
//						yq = yq + ur.getBetChouma();
//						ur.setBetChouma(0);
//					}
//				}
//			}
			//分配
			for (int j = 0 ; j < geshu[i] + 1 ; j ++) {
				RoomPersion persion = rpss[i][j];
				if (rpss[i][j].getBetChouma() < 1) {
					continue;
				}
				double _c = count ;
				double _b = persion.getBetChouma();
				if (count < 1) {
					logger.error("@@ 计算筹码出差哦.........");
					_c = 1;
				}
				Double a = yq * (_b/_c) + 0.5;//四舍五入
				persion.setNowcounma(persion.getNowcounma() + persion.getBetChouma() + a.intValue());
				persion.setYq(persion.getYq() + a.intValue());
				persion.setBetChouma(0);
			}
		}
		//记录正常场log
		if (room.getRoomType() == 1) {
			for (RoomPersion r1 : room.getRoomPersions()) {
				if (r1 != null) {
//					LogManage.putType1GameLog1(r1, room);
				}
			}
//			for (int i2 = 0 ; i2 < room.getDeletePersion().getSize() ; i2 ++) {
//				LogManage.putType1GameLog1(room.getDeletePersion().getRoomPrsions()[i2], room);
//			}
		}

		// 胜负 积分控制
		for (int i2 = 0 ; i2 < room.getRoomPersions().length ; i2 ++) {
			RoomPersion rp_ = room.getRoomPersions()[i2];
			if (rp_ != null) {
				//记录游戏积分
				if (room.getRoomType() == 1) {
//					rp_.getUserInfo().setAllJifen(rp_.getYq());
				}
				//记录场数
				rp_.setAc(rp_.getAc() + 1);
				if (rp_.getYq() > 0){
					rp_.setWc(rp_.getWc() + 1);
					rp_.getUserInfo().setWin(rp_.getUserInfo().getWin() + 1);
					rp_.setYs(1);
					if ((rp_.getYq() + rp_.getLastChouma()) > rp_.getUserInfo().getBiggestwinRate()) {
						rp_.getUserInfo().setBiggestwinRate(rp_.getYq() + rp_.getLastChouma());
						rp_.getUserInfo().setIsBiggestwinRate(1);
					}else {
						rp_.getUserInfo().setIsBiggestwinRate(-1);
					}
				}else {
					rp_.getUserInfo().setLose(rp_.getUserInfo().getLose() + 1);
					rp_.setYs(-1);
				}
			}
		}
		objs[0] = bipaijieguo(rpss);
		logger.debug("bi pai ...OK");

		//考虑如果房间是比赛场地
		if (room.getRoomType() == 2) {
//			bishai((Integer)objs[0]);
//			for (int i2 = 0 ; i2 < room.getDeletePersion().getSize() ; i2 ++) {
//				room.getDeletePersion().getRoomPrsions()[i2].setNowcounma(0);
//				room.getDeletePersion().getRoomPrsions()[i2].setYq(-room.getChouma());
//				LogManage.putType2GameLog2(room.getDeletePersion().getRoomPrsions()[i2], room);
//			}
		}else {
			//记录log 

			//如果是游戏场更新绑定的筹码
//			PersionChipBindDao pcb = new PersionChipBindDaoImp();
//			try {
//				pcb.updatBindAll(room.getRoomPersions());
//			} catch (Exception e) {
//				logger.error("PersionChipBindDao ..ERROR", e);
//			}
//			for (RoomPersion rp : room.getRoomPersions()) {
//				if (rp != null) {
//					rp.setType(1);
//				}
//			}
		}
//		room.getDeletePersion().clear();
		return objs;
	}

	/**
	 * 最大牌 牌类型 和
	 *
	 * @param pocer 需要比的七张牌
	 * @return
	 */
	public static Object[] zuidapai(Pocer[] pocer) {
		return BiPai.zuidapai(pocer);
	}

	/**
	 * 清空 本轮玩家已经下的筹码
	 */
	public void clearAuneCount() {
		for (RoomPersion r : room.getRoomPersions()) {
			if (r != null) {
				r.setAnteCount(0);
			}
		}
	}

	/**
	 * 比赛场逻辑处理
	 */
//	private void bishai(Integer winCount) {
//		//筹码==0的就淘汰（倒数 2-3淘汰发送名次）
//		//决出最后一名本盘游戏结束 所有人站起
//		//未结束需要加大小盲注
//		int a = 0;//需要淘汰的人
//		int b = 0;//不需要淘汰的人
//		RoomPersion[] as = new RoomPersion[7];
//		RoomPersion[] bs = new RoomPersion[7];
//		Integer[] rankint = null;
//		Integer[] indexs = null;
//		Integer[] userids = null;
//		Integer[] golds = null;
//		for (int i = 0 ; i < room.getRoomPersions().length ; i ++) {
//			RoomPersion rp = room.getRoomPersions()[i];
//			if (rp == null) {
//				continue;
//			}
//			if (rp.getOnlinerType() == -1) {
//				//保存用户信息
//				try {
//					updateUserInfo(rp);
//				} catch (SQLException e) {
//					e.printStackTrace();
//					logger.error("保存用户信息出差!", e);
//				}
//				room.getRoomPersions()[i] = null;
//				continue;
//			}
//			if (rp.getNowcounma() < 1) {
//				//淘汰
//				as[a] = rp;
//				a ++;
//			}else {
//				bs[b] = rp;
//				b ++;
//			}
//		}
//		if (b == 0) {
//			logger.error("房间进程逻辑有错..........");
//			closeRoom2();
//		}
//
//		int c = a;
//		if (b == 1) {
//			c = c + b;
//		}
//		indexs = new Integer[c];
//		userids = new Integer[c];
//		golds = new Integer[c];
//		rankint = new Integer[c];
//		if (b >= 2) {
//			//直接淘汰没商量
//			if (a > 0) {
//				for (int i = 0 ; i < a ; i ++) {
//					RoomPersion rp = as[i];
//					//记录游戏比赛积分
//					rp.getUserInfo().setAllJifen(0 - room.getChouma());
//					rp.getUserInfo().setJifen2(rp.getUserInfo().getJifen2() -1);
//					rp.setType(1);
//					rp.setStatus(0);
//					indexs[i] = rp.getSize();
//					userids[i] = rp.getUserId();
//					golds[i] = -1;
//					rankint[i] = -1;
//					room.getRoomPersions()[rp.getSize()] = null;
//					//保存用户信息
//					try {
//						updateUserInfo(rp);
//					} catch (SQLException e) {
//						e.printStackTrace();
//						logger.error("保存用户信息出差!", e);
//					}
//					//记录比赛信息log
//					rp.setNowcounma(0);
//					rp.setYq(-room.getChouma());
//					LogManage.putType2GameLog2(rp, room);
//				}
//			}
//			room.setBisaiCount(room.getBisaiCount() + 1);
//			if (room.getBisaiCount() % 4 == 0) {
//				room.setManzhu(room.getManzhu() * 2);
//				room.setDamanzhu(room.getDamanzhu() * 2);
//			}
//			room.setBisaiStatus(2);
//		}else if (b == 1) {
//			//被淘汰的人是地二名
//			//本盘游戏结束
//			if (a > 0) {
////				int d = new Double((new Double(room.getChouma() * RoomCourse.size * 0.25))/a + 0.5).intValue();
//				int d = new Double((new Double(room.getD2()))/a + 0.5).intValue();
//				for (int i = 0 ; i < a ; i ++) {
//					RoomPersion rp = as[i];
//					//记录游戏比赛积分
//					rp.getUserInfo().setAllJifen(d);
//					rp.getUserInfo().setJifen2(rp.getUserInfo().getJifen2() + 2);
//					rp.setType(1);
//					rp.setStatus(0);
//					indexs[i] = rp.getSize();
//					userids[i] = rp.getUserId();
//					golds[i] = d;
//					rp.setChouma(rp.getChouma() + d);
//					rankint[i] = 2;
//					if (d > rp.getUserInfo().getBiggestwinRate()) {
//						rp.getUserInfo().setBiggestwinRate(d);
//					}
//					room.getRoomPersions()[rp.getSize()] = null;
//					//保存用户信息
//					try {
//						updateUserInfo(rp);
//					} catch (SQLException e) {
//						e.printStackTrace();
//						logger.error("保存用户信息出差!", e);
//					}
//					//记录比赛信息log
//					rp.setNowcounma(0);
//					rp.setYq(d);
//					LogManage.putType2GameLog2(rp, room);
//				}
//			}
//
//			//组装第一名数据
//			golds[c - 1] = new Double(room.getD1()).intValue();
//			indexs[c -1] = bs[0].getSize();
//			userids[c - 1] = bs[0].getUserId();
//			rankint[c -1] = 1;
//			try {
//				room.getRoomPersions()[bs[0].getSize()].setType(1);
//				room.getRoomPersions()[bs[0].getSize()].setStatus(0);
//			} catch (Exception e) {
//				logger.error(".", e);
//			}
//			room.getRoomPersions()[bs[0].getSize()] = null;
//			bs[0].setChouma(bs[0].getChouma() + golds[c - 1]);
//
//			//记录游戏比赛积分
//			bs[0].getUserInfo().setAllJifen(golds[c - 1]);
//			bs[0].getUserInfo().setJifen2(bs[0].getUserInfo().getJifen2() + 3);
//			if (golds[c - 1] > bs[0].getUserInfo().getBiggestwinRate()) {
//				bs[0].getUserInfo().setBiggestwinRate(golds[c - 1]);
//			}
//			//保存用户信息
//			try {
//				updateUserInfo(bs[0]);
//			} catch (SQLException e) {
//				e.printStackTrace();
//				logger.error("保存用户信息出差!", e);
//			}
//			room.setBisaiCount(0);
//			room.setBisaiStatus(3);
//			room.clearManzhu();
//			//还原相关状态
//			for (RoomPersion rp_ : room.getRoomPersions()) {
//				if (rp_ != null) {
//					rp_.setType(1);
//					rp_.setStatus(0);
//				}
//			}
//			//记录比赛信息log
//			bs[0].setNowcounma(0);
//			bs[0].setYq(golds[c - 1]);
//			LogManage.putType2GameLog2(bs[0], room);
//		}
//
//		try {
//			winCount = winCount < 1 ? 1 : winCount;
//			Thread.sleep(Constant.BIPAI_TIME + (Constant.WIN_WAIT_TIME * (winCount - 1)));
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//			logger.debug("比赛场地出错", e);
//		}
//		if (a > 0 || b == 1) {
//			//通知结果
//			Object[][] objs3 = {
//					{60,a > 1 ? 0 : 1,I366ClientPickUtil.TYPE_INT_1},
//					{132,rankint,I366ClientPickUtil.TYPE_INT_1_ARRAY},
//					{133,indexs,I366ClientPickUtil.TYPE_INT_1_ARRAY},
//					{130,userids,I366ClientPickUtil.TYPE_INT_4_ARRAY},
//					{131,golds,I366ClientPickUtil.TYPE_INT_4_ARRAY}
//			};
//			byte[] bytes = I366PickUtil.packAll(objs3, Constant.REQ_GAME_RECV_OUT);
//			send(bytes);
//			if (rankint[rankint.length -1] == null) {
//				logger.error("rankint[rankint.length -1] is null!!!");
//			}
//			if (rankint[rankint.length -1] == 1) {
//				room.setRoomStatus(1);
//			}
//		}
//	}

	/**
	 * 两对牌对比查看那个大 -1一样大 0：rp1大       1：rp2大
	 *
	 * @param rp1
	 * @param rp2
	 * @return
	 */
	public static int bipai2(RoomPersion rp1 ,RoomPersion rp2) {
		return BiPai.bipai2(rp1, rp2);
	}


	protected static void swap(Object[] array, int i, int j) {
		Object temp;
		temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}
	protected static void swap(int[] array, int i, int j) {
		int temp;
		temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}


//    public static void main(String[] args) {
//    	int array[] = {12,23,5,5,3,53,6};
//        // 冒泡是一种简单的交换排序[O(n*n)]
//        for (int i = 0; i < array.length; i++)
//            for (int j = 0; j < array.length - i - 1; j++)
//                if (array[j] > array[j + 1])// 小的往上冒,由大到小
//                    swap(array, j, j + 1);
//        for (int i : array) {
//        	System.out.println(i);
//        }
//    }



	/**
	 * 获取当前房间情况数据
	 * @return
	 */
	public synchronized byte[] getRoomDate(int mySeatID) {
		return getRoomDate2( mySeatID);
	}

	/**
	 * 获取当前房间情况数据
	 * @return
	 */
	public byte[] getRoomDate2(int mySeatID) {
		int status = 0;
		int gamestatus = -1;
		int countdowntimes = -1;
		if ( 3 <= room.getRoomStatus() && room.getRoomStatus() <= 6) {
			gamestatus = 1;
		}else if (room.getRoomStatus() == 2) {
			gamestatus = 0;
			Long t = (Constant.STATUS_2_DC -(System.currentTimeMillis() - room.getT2()))/1000;
			countdowntimes = t.intValue();
		}else {
			gamestatus = -1;
		}
		if (room.getRoomType() == 2) {
			if ( 3 <= room.getRoomStatus() && room.getRoomStatus() <= 6) {
				gamestatus = 3;
			}else {
				gamestatus = 2;
			}
		}
		Integer[] cards = {-1,-1,-1,-1,-1};
		for (int i=0 ; i < room.getPocer().length ; i ++) {
			if (room.getPocer()[i] != null) {
				cards[i] = room.getPocer()[i].getSize1();
			}else {
				break;
			}
		}
		Long[] playerIdArray = new Long[8];
		//1:下注  2:跟注  3:加注  4:全下 5:让牌  6:弃牌 7托管 8等待下一盘
		Integer[] statusArray = new Integer[8];
		Integer[] anteArray = new Integer[8];
		StringBuilder nickString = new StringBuilder();
		Integer[] chipsArray = new Integer[8];
		StringBuilder headPicString = new StringBuilder();
		Integer[] firstCardArray = new Integer[8];
		Integer[] secondCardArray = new Integer[8];
		Integer alreadyAnte = 0;
		int test = 0;
		int maxAnte = 0; //本轮最大下注筹码
		for (int i=0 ; i < room.getRoomPersions().length ; i ++) {
			RoomPersion roomPersion = room.getRoomPersions()[i];
			if (roomPersion == null || roomPersion.getOnlinerType() == -1) {
				roomPersion = room.getDdRoomPersions()[i];
			}
			if (roomPersion == null || roomPersion.getOnlinerType() == -1) {
				playerIdArray[i] = -1L;
				statusArray[i] = -1;
				anteArray[i] = -1;
				if (i == 0) {
					nickString.append("null");
					headPicString.append("null");
				}else {
					nickString.append(sp).append("null");
					headPicString.append(sp).append("null");
				}
				chipsArray[i] = -1;
				firstCardArray[i] = -1;
				secondCardArray[i] = -1;
			}else {
				if (i == 0) {
					nickString.append(trimString(roomPersion.getUserInfo().getNikeName()));
					headPicString.append(roomPersion.getUserInfo().getHead());
				}else {
					nickString.append(sp).append(trimString(roomPersion.getUserInfo().getNikeName()));
					headPicString.append(sp).append(roomPersion.getUserInfo().getHead());
				}

				playerIdArray[i] = roomPersion.getUserId();
				if (roomPersion.getType() == 2 || roomPersion.getType() == 4) {
					statusArray[i] = 8; //等待下一盘
					anteArray[i] = -1;
				}else {
					statusArray[i] = roomPersion.getClientStatus();
					anteArray[i] = roomPersion.getAnteCount();
					test = test + roomPersion.getAnteCount();
					if (maxAnte < roomPersion.getAnteCount()) {
						maxAnte = roomPersion.getAnteCount();
					}
				}
				chipsArray[i] = roomPersion.getNowcounma();
				firstCardArray[i] = roomPersion.getPocers()[0] == null ? -1 : roomPersion.getPocers()[0].getSize1();
				secondCardArray[i] = roomPersion.getPocers()[1] == null ? -1 : roomPersion.getPocers()[1].getSize1();
				alreadyAnte = alreadyAnte + roomPersion.getBetChouma();
			}
		}
		//添加筹码池筹码
		MessageStruct.EnterRoomResp.Builder builder = MessageStruct.EnterRoomResp.newBuilder();
		builder.setStatus(status);
		builder.setGameStatus(gamestatus);
		builder.setCountdowntimes(countdowntimes);
		builder.setDamangzhu(room.getDamanzhu());
		builder.setMangzhu(room.getManzhu());
		builder.setDamangzhuindex(room.getDamanzhuNumber());
		builder.setMangzhuindex(room.getManzhuNumber());
		builder.setZhuangjiaindex(room.getZhuangjiaNumber());
		builder.setCurrentindex(room.getCurrentNumber());
		builder.setWait(room.getWait());
		builder.setMySeat(mySeatID);
		builder.addAllCards(Arrays.asList(cards));
		builder.addAllPlayerIdList(Arrays.asList(playerIdArray));
		builder.addAllStatusList(Arrays.asList(statusArray));
		builder.addAllXiazhuList(Arrays.asList(anteArray));
		builder.setNickName(nickString.toString());
		builder.addAllChipList(Arrays.asList(chipsArray));
		builder.setHead(headPicString.toString());
		builder.addAllFirstCardList(Arrays.asList(firstCardArray));
		builder.addAllSecondCardList(Arrays.asList(secondCardArray));
		builder.setMaxChoumaThisRound(maxAnte);
		return builder.build().toByteArray();
	}

	/**
	 * 最大牌机器人处理
	 *1  找到5张最大牌 放入puck中并指定给某个ID用户 -1情况下则不管
	 *2 玩家在获取牌时需要指定是否是某个ID
	 */
	private void zuidapaiJIqren() {
		long userId = -1;
		room.setZuidajiqrenId(userId);
		//洗牌
		room.getPocerLink().shuffle(userId);
	}

	private static Random r = new Random();
	/**
	 * 通知开始游戏 设置玩家状态 并发两张底牌 
	 * 1、先扣服务费
	 */
	public synchronized void beginGemeOne() {
		//并符合开局条件则不开局
		if (room.getRoomType() == 1) {
			int count = 0;
			for (int i = 0 ; i < room.getRoomPersions().length ; i ++) {
				if (room.getRoomPersions()[i] != null && room.getRoomPersions()[i].getNowcounma() >= (room.getFuwufei() + room.getDamanzhu())) {
					count ++;
				}
			}
			if (count < 2) {
				room.setRoomStatus(1);//重新开始等待
				return;
			}
		}

		//指定大小盲注
		nextmanzhu();
		logger.debug("beginGemeOne .....");
		zuidapaiJIqren();
		Integer[] firstCardArray = new Integer[8];
		Integer[] secondCardArray = new Integer[8];
		Integer[] chipsArray = new Integer[8];
		int i = 0;
		//----
		Integer daojishi[] = new Integer[8];
		int debug = -99;
		for (RoomPersion p : room.getRoomPersions()) {
			if (p != null) {
				//先把服务费用扣了
				if (room.getRoomType() == 1) {
					p.setNowcounma(p.getNowcounma() - room.getFuwufei());
				}
				if (p.getAddUpTime() < 1) {
					p.setAddUpTime(System.currentTimeMillis());
				}
				p.setIsGame(1);
				p.setType(3);
//				p.setAnteCount(0);
				p.setAnteNumber(0);
				Pocer pocer1 = room.getPocerLink().robotNext(room.getZuidajiqrenId() == p.getUserId() ? 1 : 3);
				debug = pocer1.getSize1();
				p.getPocers()[0] = pocer1;
				p.putHoleCard(new Card(pocer1.getSuit(), pocer1.getNumber()));
				firstCardArray[i] = pocer1.getSize1();
				Pocer pocer2 = room.getPocerLink().robotNext(room.getZuidajiqrenId() == p.getUserId() ? 1 : 3);
				p.getPocers()[1] =pocer2;
				p.putHoleCard(new Card(pocer2.getSuit(), pocer2.getNumber()));
				secondCardArray[i] = pocer2.getSize1();
				chipsArray[i] = p.getNowcounma();
				if (pocer1.getSize1() < 0 || pocer1.getSize1() > 51 || pocer2.getSize1() < 0 || pocer1.getSize2() > 51) {
					logger.error("size1:" + pocer1.getSize1() + " size2:" + pocer2.getSize2());
					logs();
				}
				//
				//记录倒计时

			}else {
				firstCardArray[i] = -1;
				secondCardArray[i] = -1;
				chipsArray[i] = -1;
				daojishi[i] = -1;
			}
			i ++;
		}
		MessageStruct.GameStart.Builder builder = MessageStruct.GameStart.newBuilder();
		builder.setZhuangjiaIdx(room.getZhuangjiaNumber());
		builder.setDamangzhuIdx(room.getDamanzhuNumber());
		builder.setMangzhuIdx(room.getManzhuNumber());
		builder.setCurIdx(room.getCurrentNumber());
		builder.addAllFirstCardList(Arrays.asList(firstCardArray));
		builder.addAllSecondCardList(Arrays.asList(secondCardArray));
		builder.setMangzhu(room.getManzhu());
		builder.setDamangzhu(room.getDamanzhu());
		builder.addAllChipsList(Arrays.asList(chipsArray));
//		byte[] bytes = I366PickUtil.packAll(objs, Constant.REQ_GAME_RECV_START_INFOR);
		broadcast(CommandEnum.S2C_GAME_START_RESP, builder.build().toByteArray());
		//打印相关开局信息
		logger.debug("-------////////kai ju///////-------roomId:" + room.getRoomId());
		logger.debug("tow poker :");
		logger.debug(firstCardArray[0] + "/" + firstCardArray[1] + "/" + firstCardArray[2] + "/"+ firstCardArray[3] + "/"+ firstCardArray[4] + "/"+ firstCardArray[5] + "/"+ firstCardArray[6] + "/"+ firstCardArray[7]);
		logger.debug(secondCardArray[0] + "/" + secondCardArray[1] + "/" + secondCardArray[2] + "/"+ secondCardArray[3] + "/"+ secondCardArray[4] + "/"+ secondCardArray[5] + "/"+ secondCardArray[6] + "/"+ secondCardArray[7]);
		RoomPersion[] rps = room.getRoomPersions();
		logger.debug((rps[0]==null?"null":(""+rps[0].getSize()+rps[0].getUserId())) + "/" +
						(rps[1]==null?"null":(""+rps[1].getSize()+rps[1].getUserId())) + "/" +
						(rps[2]==null?"null":(""+rps[2].getSize()+rps[2].getUserId())) + "/" +
						(rps[3]==null?"null":(""+rps[3].getSize()+rps[3].getUserId())) + "/" +
						(rps[4]==null?"null":(""+rps[4].getSize()+rps[4].getUserId())) + "/" +
						(rps[5]==null?"null":(""+rps[5].getSize()+rps[5].getUserId())) + "/" +
						(rps[6]==null?"null":(""+rps[6].getSize()+rps[6].getUserId()))+ "/" +
						(rps[7]==null?"null":(""+rps[7].getSize()+rps[7].getUserId()))
		);
		logger.debug("manzhu:" + room.getManzhu() + "/manzhunumber:" + room.getManzhuNumber() + " /damanzhunumber:" + room.getDamanzhuNumber() + "/zhuanjianumber:" + room.getZhuangjiaNumber() );
		logger.debug("-------///////////////-------");
		//
		if (debug < 0) {
			logs();
			logger.error("pocer err.....");
		}
		//本轮玩家设置下注的筹码
		//设置相关状态
		room.setRoomStatus(3);//准备第一轮投注
		room.setBisaiStatus(2);
		room.setT3(System.currentTimeMillis());
		logger.debug("beginGemeOne .....OK");
	}

	private void logs() {
		logger.error("||||||--------------begin error-----------------||||||");
		try {
			logger.debug("roomId/roomStatus/getBisaiStatus:" + room.getRoomId() + "/" + room.getRoomStatus() + "/" + room.getBisaiStatus());
			logger.debug("room audMap:");
			Object[] audMapObjects = room.getAudMap().values().toArray();
			for (Object audObject : audMapObjects) {
				if (audMapObjects != null) {
					RoomPersion rp = (RoomPersion) audObject;
					logger.debug("userId/chip/nowChip/type/status:" + rp.getUserId() + "/" + rp.getChouma() + "/" + rp.getNowcounma() + "/" + rp.getType() + "/" + rp.getStatus());
				}
			}
			logger.debug("roomPersions :");
			for (RoomPersion rp  : room.getRoomPersions()) {
				if (rp != null) {
					logger.debug("userId/chip/nowChip/type/status:" + rp.getUserId() + "/" + rp.getChouma() + "/" + rp.getNowcounma() + "/" + rp.getType() + "/" + rp.getStatus());
				}
			}
		} catch (Exception e2) {
			logger.error("roomThreadTrim err + roomid:" + room.getRoomId(), e2);
		}
		logger.error("||||||--------------2manzhu error-----------------||||||");
	}

	/**
	 * 通知玩家操作
	 * @param playerId 当前操作玩家编号
	 * @param seatId 座位编号
	 * @param actionStatus 玩家操作
	 * @param anteNumber  下注筹码数
	 * @param operationId  下一个下注玩家的座位id
	 * @param userId 排除的用户
	 */
	public void gameAction(long playerId , int seatId ,int actionStatus ,int anteNumber , int operationId , long userId , int z) {
		byte[] bytes = MessageStruct.GameRoundAction.newBuilder().setUserId(playerId).setSeatId(seatId).setActionStatus(actionStatus)
				.setLastXiazhuChouma(anteNumber).setOptUserId(operationId).build().toByteArray();
		if (z == 1) {
			broadcast(CommandEnum.S2C_GAME_ROUND_ACTION_RESP, bytes);
		}else {
			sendExcept(CommandEnum.S2C_GAME_ROUND_ACTION_RESP, bytes , userId);
		}

	}

	/**
	 * 发公共牌
	 *
	 * @param count 发几张
	 * @param size  当前操作玩家
	 */
	public synchronized void sendCards(int count , int size) {
		sendCards2(count , size);
	}


	// 发放公共牌
	public void sendCards2(int count , int size) {
		if (count == 0) {
			return;
		}
//		logger.debug("sendCards ....");
		Integer[] systemCards = new Integer[count];
		int onSize = 0;
		for (int i = 0 ; i < room.getPocer().length ; i ++) {
			if (room.getPocer()[i] == null) {
				onSize = i;
				break;
			}
		}
		for (int i = 0 ; i < count ; i ++) {
			Pocer p = room.getPocerLink().robotNext(2);
			room.getPocer()[i + onSize] = p;
			systemCards[i] = room.getPocer()[i + onSize].getSize1();
			room.putSharedCard(new Card(p.getSuit(), p.getNumber()));
		}
		byte[] bytes = MessageStruct.PublicCard.newBuilder().setSize(size).addAllPubCards(Arrays.asList(systemCards)).build().toByteArray();
		broadcast(CommandEnum.S2C_GOT_PUBLIC_CARD, bytes);
	}
	/**
	 * 通知所有用户
	 *
	 * @param bytes
	 */
	public void broadcast(CommandEnum message, byte[] bytes) {
		Object[] objs = room.getAudMap().values().toArray();
		for (Object obj : objs) {
			if (obj != null) {
				RoomPersion rp = (RoomPersion)obj;
				UserInfo userInfo = rp.getUserInfo();
				if (userInfo == null) {
					logger.debug("err-----send err userId/userRoomId is : " + rp.getUserId()  + " this roomId is:" + room.getRoomId());
					continue;
				}
				if (userInfo != null && userInfo.getRoomId() == room.getRoomId() && rp.getOnlinerType() == 1) {
					userInfo.getPlayer().sendMessage(message, bytes);
				}else {
					logger.debug("send err userId/userRoomId is : " +rp.getUserId()  + " this roomId is:" + room.getRoomId());
				}
			}
		}
	}

	/**
	 * 通知其它玩家
	 *
	 * @param bytes
	 */
	public void sendExcept(CommandEnum command, byte[] bytes, long usId) {
		Object[] objs = room.getAudMap().values().toArray();
		for (Object obj : objs) {
			if (obj != null) {
				RoomPersion rp = (RoomPersion)obj;
				if (rp.getUserId() != usId) {
					UserInfo userInfo = rp.getUserInfo();
					if (userInfo == null) {
						logger.debug("err-----send err userId/userRoomId is : " + rp.getUserId()  + " this roomId is:" + room.getRoomId());
						continue;
					}
					if (userInfo != null && userInfo.getRoomId() == room.getRoomId() && rp.getOnlinerType() == 1) {
						userInfo.getPlayer().sendMessage(command, bytes);
					}else {
						logger.debug("send err userId/userRoomId is : " +rp.getUserId()  + " this roomId is:" + room.getRoomId());
					}
				}
			}
		}
	}

	/**
	 * 通知某个玩家
	 *
	 * @param bytes
	 */
	public void sendByUserId(CommandEnum command, byte[] bytes, int userId) {
		RoomPersion rp = room.getAudMap().get(userId);
		UserInfo userInfo = rp.getUserInfo();
		if (userInfo == null) {
			logger.debug("err-----send err userId/userRoomId is : " + userId  + " this roomId is:" + room.getRoomId());
			return;
		}
		if (userInfo != null && userInfo.getRoomId() == room.getRoomId() && rp.getOnlinerType() == 1) {
			userInfo.getPlayer().sendMessage(command, bytes);
		}else {
			logger.debug("send err userId/userRoomId is : " + userInfo.getUserId() + " this roomId is:" + room.getRoomId());
		}
	}

	public static String trimString(String str) {
		return str.replace("@%", "");
	}



	/**
	 * 玩家超时操作
	 *
	 * @param userInfo
	 */
	public void userTimeOut2(UserInfo userInfo) {
		if (room != null) {
			RoomPersion persion = room.getAudMap().get(userInfo.getUserId());
			if (persion != null) {
				likai2(persion, -1);
			}
		}
	}

	/**
	 * 玩家超时操作
	 *
	 * @param userInfo
	 */
	public synchronized void userTimeOut(UserInfo userInfo) {
		userTimeOut2(userInfo);
	}
}

